<template>
    <div>
      <el-container>
        <el-header :style="setDynamicHeight(0.1)">
        </el-header>
        <el-main>
          <el-row>
            <el-col class="whiteBackground" :span="5" :style="setDynamicHeight(0.8)"></el-col>
            <el-col class="sidebar" :span="1" :style="setDynamicHeight(0.8)">
              <sidebar ref="sidebar" :getUserInfo="getUserInfo"></sidebar>
            </el-col>
            <el-col class="friendList" :span="4" :style="setDynamicHeight(0.8)">
              <friend-list ref="friendList" :pubSessionIdVue="pubSessionIdVue" :changeSessionId="changeSessionId"></friend-list>
            </el-col>
            <el-col class="chatBox" :span="9" :style="setDynamicHeight(0.8)">
              <chat-box ref="chatBox"
                        :avatarUrl="avatarUrl"
                        :userName="userName"
                        :pubSessionIdVue="pubSessionIdVue"
                        :sendMessage="sendMessage"></chat-box>
            </el-col>
            <el-col class="whiteBackground" :span="5" :style="setDynamicHeight(0.8)"></el-col>
          </el-row>
        </el-main>
        <el-footer :style="setDynamicHeight(0.1)"></el-footer>
        <login-dialog ref="loginDialog" :checkLogin="checkLogin"></login-dialog>
      </el-container>
    </div>
</template>

<script>
    import friendList from "./friendList";
    import sidebar from "./sidebar";
    import chatBox from "./chatBox";
    import loginDialog from "./loginDialog";
    import Vue from 'vue'
    export default {
      name: "index",
      components: {
        friendList,
        sidebar,
        chatBox,
        loginDialog
      },
      data () {
        return {
          path: 'ws://cgx.com/live-chat/webSocket',
          socket: {},
          pubSessionIdVue: new Vue(),
          sessionId: '',
          avatarUrl: '',
          userName: ''
        }
      },
      mounted () {
        // 初始化
        this.init()
      },
      methods: {
        init() {
          this.checkLogin();
        },
        async getUserInfo(userId) {
          const paramObj = {userId: this.$cookieStore.getCookie("userId")};
          const result = await this.$api.user.info(paramObj);
          if (result.code === 0) {
            this.avatarUrl = result.data.avatarUrl;
            this.userName = result.data.userName;
            this.$refs.sidebar.changeHeadPortrait(result.data.avatarUrl);
          } else {
            this.$message.error(result.msg);
          }
        },
        checkLogin() {
          const userId = this.$cookieStore.getCookie("userId");
          const token = this.$cookieStore.getCookie("token");
          if (!userId || !token) {
            return this.$refs.loginDialog.showDialog();
          }
          this.getUserInfo();
          this.$refs.friendList.getSessionList(userId);
          this.createWebSocket();
        },
        createWebSocket() {
          // 实例化socket
          const webSocketPath = this.path + '?userId=' + this.$cookieStore.getCookie("userId");
          this.socket = new WebSocket(webSocketPath);
          // 监听socket连接
          this.socket.onopen = this.onopen;
          // 监听socket错误信息
          this.socket.onerror = this.onerror;
          // 监听socket消息
          this.socket.onmessage = this.onmessage;
          //  心跳
          this.heartbeat();
        },
        onopen() {
          console.log('onopen');
        },
        onerror() {
          console.log('onerror');
        },
        onmessage (msg) {
          console.log('onmessage');
          console.log(msg);
          this.messageProcessor(msg);
        },
        sendMessage(message) {
          this.socket.send(JSON.stringify(message))
        },
        changeSessionId(sessionId) {
          this.sessionId = sessionId;
        },
        heartbeat() {
          const timer = setInterval(()=>{
            console.log('heartbeat');
            const message = {};
            message.type = -1;
            this.socket.send(JSON.stringify(message));
          },5 * 60 * 1000);
          this.$once('hook:beforeDestroy', ()=>{
            clearInterval(timer)
          });
        },
        messageProcessor(msg) {
          const message = JSON.parse(msg.data);
          if (1 === message.type || 0 === message.type) {
            this.userMessageProcessor(message);
          }
        },
        userMessageProcessor(message){
          if (this.sessionId === message.sessionId) {
            this.$refs.chatBox.addMessageAndJump(message);
          }
          this.$refs.friendList.addMessageBySessionId(message.sessionId);
        }
      }
    }
</script>

<style scoped>
  .el-container {
    margin-top: 0;
  }
  .el-header, .el-footer {
    background-color: #41444B;
    color: #333;
    text-align: center;
    line-height: 60px;
  }
  .el-main {
    overflow-y: hidden;
    background-color: #41444B;
    color: #333;
    padding: 0;
  }
  .whiteBackground {
    background-color: #41444B;
  }
  .sidebar {
    border-top-left-radius: 2px;
    border-bottom-left-radius: 2px;
    background-color: #28292C;
  }
  .friendList {
    background-color: #ECE9E8;
    border-right-style: solid;
    border-top-style:solid;
    border-bottom-style: solid;
    border-width: 1px;
    border-color: #D6D6D6;
  }
  .chatBox {
  }
</style>
